package com.htht.smartschool.service.card;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.htht.smartschool.amq.SeniorMessageSender;
import com.htht.smartschool.common.service.BaseService;
import com.htht.smartschool.model.amq.Mstatus;
import com.htht.smartschool.model.card.Rings;
import com.htht.smartschool.model.card.TBdworkhour;
import com.htht.smartschool.model.card.TCard;
import com.htht.smartschool.model.card.TFamilyphone;
import com.htht.smartschool.model.card.TPhonebook;
import com.htht.smartschool.model.card.TPhonebooktemp;
import com.htht.smartschool.model.card.TSosphone;
import com.htht.smartschool.model.common.TUserStudent;
import com.htht.smartschool.model.message.TMessage;
import com.htht.smartschool.util.cmpp.CmppData;
import com.htht.smartschool.util.cmpp.CmppUtil;
import com.htht.smartschool.util.message.MessageUtil;
import com.htht.smartschool.util.redis.RedisKeyConstant;
import com.htht.smartschool.util.redis.RedisUtil;
import com.htht.smartschool.util.system.DateUtil;
import com.htht.smartschool.util.system.GsonUtils;

public class CardService extends BaseService {
	public TCard addCard(TCard card) {
		card = (TCard) getDao().create(card);
		return card;
	}
	
	@SuppressWarnings("rawtypes")
	public TUserStudent getUSIByImei(String imei) {
		String sql = "SELECT tus.imei,tus.studentcode,tus.usercode,tu.messageid,ts.name FROM t_user_student tus,t_user tu,t_student ts "
				+ " WHERE tus.imei =:imei and tu.usercode = tus.usercode and tus.studentcode = ts.studentcode";
		TUserStudent tust = new TUserStudent();
		tust.setImei(imei);
		List list = getDao().queryBySQL(sql,tust);
		if(list.size() == 0){
			return null;
		}else{
			Object[] obj =  (Object[]) list.get(0);
			TUserStudent tus = new TUserStudent();
			tus.setImei(String.valueOf(obj[0]));
			tus.setStudentcode(String.valueOf(obj[1]));
			tus.setUsercode(String.valueOf(obj[2]));
			List<Long> to = new ArrayList<Long>();
			to.add(Long.valueOf(String.valueOf(obj[3])));
			tus.setTo(to);
			tus.setStuname(String.valueOf(obj[4]));
			return tus;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<TCard> getCard(TCard card) {
		String sql = "SELECT DISTINCT tc.*,tcl.classcode FROM t_card tc,t_class tcl,t_student ts WHERE tc.studentcode = ts.studentcode AND ts.classcode = tcl.classcode ";
		if(card.getImei() != null && !card.getImei().equalsIgnoreCase("")){
			sql += " and tc.imei = :imei";
		}
		if(card.getStudentcode() != null && card.getStudentcode().length()> 0){
			sql += " and tc.studentcode = :studentcode";
		}
		if(card.getCellphone() != null && card.getCellphone().length()> 0){
			sql += " and tc.cellphone= :cellphone";
		}
		List<Object[]> list = getDao().queryBySQL(sql,card);
		List<TCard> result = new ArrayList<TCard>();
		for (Object[] obj : list) {
			TCard tc = new TCard();
			tc.setId(Long.valueOf(String.valueOf(obj[0])));
			tc.setStudentcode(String.valueOf(obj[1]));
			tc.setCardcode(String.valueOf(obj[2]));
			tc.setImei(String.valueOf(obj[3]));
			tc.setCellphone(String.valueOf(obj[4]));
			tc.setRingswf(String.valueOf(obj[5]));
			tc.setRing(String.valueOf(obj[6]));
			tc.setSostype(String.valueOf(obj[7]));
			tc.setModel(String.valueOf(obj[8]));
			tc.setInvisiblecode(String.valueOf(obj[9]));
			tc.setWorkhourcode(String.valueOf(obj[10]));
			tc.setRemark(String.valueOf(obj[11]));
			tc.setClasscode(String.valueOf(obj[12]));
			result.add(tc);
		}		
		return result;
	}
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Map getCards(TCard card) {
		String sql = "SELECT DISTINCT tc.studentcode,tc.imei,tc.cellphone,ts.name,ts.headimg,tc.remark,tcl.grade,tcl.class,tcl.classcode "
				+ " FROM t_card tc,t_student ts,t_class tcl"
				+ " WHERE tc.studentcode = ts.studentcode AND ts.del =1 AND ts.classcode = tcl.classcode";
		if(card.getSchooltype() != null && card.getSchooltype().length() > 0){
			sql += " and tcl.type = :schooltype";
		}
		if(card.getClasscode() != null && card.getClasscode().length() > 0 ){
			sql += " and ts.classcode = :classcode";
		}
		if(card.getStudentname() != null && card.getStudentname().length() > 0){
			sql += " and ts.name LIKE :studentname";
			card.setStudentname("%"+card.getStudentname()+"%");
		}
		if(card.getImei() != null && card.getImei().length() > 0 ){
			sql += " and tc.imei LIKE :imei";
			card.setImei("%"+card.getImei()+"%");
		}
		if(card.getSchoolcode() != null && card.getSchoolcode().length() > 0){
			sql += " AND ts.schoolid = :schoolcode"; 
		}
		if(card.getRolecode() != null && card.getRolecode().length() > 0){
			card.setRolecode(card.getRolecode().replace(",", "^"));
			sql = "select t1.* from ("+sql+")t1,(select * from t_data_role where rolecode in (:rolecode))t2 where t1.classcode = t2.classcode";
		}
		List<Object[]> list = getDao().queryBySqlPage(sql, card,card.getCurrentpage(), card.getPagesize());
		int total = getDao().getCountBySqlPage("select count(*) from ("+sql+") co",card);
		List<TCard> result = new ArrayList<TCard>();
		try {
			for (Object[] obj: list) {
				TCard tc = new TCard();
				tc.setStudentcode(String.valueOf(obj[0]));
				tc.setImei(String.valueOf(obj[1]));
				tc.setCellphone(String.valueOf(obj[2]));
				tc.setStudentname(String.valueOf(obj[3]));
				tc.setHeadimg(String.valueOf(obj[4]));
				tc.setRemark(String.valueOf(obj[5]));
				tc.setGradeclass(String.valueOf(obj[6])+"年级"+String.valueOf(obj[7])+"班");
				result.add(tc);
			}
		} catch (Exception e) {
			System.out.println(e.toString());
			e.printStackTrace();
		}
		Map map = new HashMap();
		map.put("list", result);
		map.put("total", total);
		return map;
	}
	public TCard getCardByStudentCode(String studentcode) {
		String hql = "from TCard where studentcode = :studentcode";
		TCard tc = new TCard();
		tc.setStudentcode(studentcode);
		TCard c = (TCard) getDao().queryFirstByHQL(hql,tc);
		return c;
	}
	public boolean updateCard(TCard tcard) {
		String hql = "from TCard";
		if(tcard.getImei() != null && !tcard.getImei().equalsIgnoreCase("")){
			hql += " where imei = :imei";
		}
		TCard tc = (TCard) getDao().queryFirstByHQL(hql,tcard);
		for (Field f : tcard.getClass().getDeclaredFields()) {
		    f.setAccessible(true);
		    try {
				if (f.get(tcard) != null && !f.getName().equalsIgnoreCase("serialVersionUID")) {
				   f.set(tc, f.get(tcard));
				}
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		updateCardSystem(tcard);
		if(tcard.getRing() != null && !tcard.getRing().equalsIgnoreCase("") && !tcard.getRing().equalsIgnoreCase("null")){
			tc.setRingswf("/card/ring/"+tcard.getRing()+".swf");
		}
		boolean flag = false;
		TCard tca = (TCard) getDao().update(tc);
		if(tca != null){
			flag = true;
		}
		return flag;
	}
	public void updateCardSystem(TCard tc) {
		String mess = "";
		if(tc.getSostype() != null && !tc.getSostype().equalsIgnoreCase("") && !tc.getSostype().equalsIgnoreCase("null")){
			if(tc.getSostype().equalsIgnoreCase("4")){
				mess = tc.getImei()+":SOSALM:SOSALM,OFF#";
			}else{
				mess = tc.getImei()+":SOSALM:SOSALM,ON,"+tc.getSostype()+"#";
			}
		}else if(tc.getRing() != null && !tc.getRing().equalsIgnoreCase("") && !tc.getRing().equalsIgnoreCase("null")){
			mess = tc.getImei()+":RING:RING,"+tc.getRing()+"#";
		}else if(tc.getModel() != null && !tc.getModel().equalsIgnoreCase("") && !tc.getModel().equalsIgnoreCase("null")){
			mess = tc.getImei()+":CALLMODE:CALLMODE,"+tc.getModel()+"#";
		}
		SeniorMessageSender.sendMessage(mess);
	}

	public boolean deleteCard(TCard card) {
		boolean flag = getDao().delete(card);
		return flag;
	}

	public boolean addPhonebooks(TPhonebook book) {
		TCard card = new TCard();
		card.setImei(book.getImei());
		List<TPhonebook> list = getPhonebooks(card);
		boolean flag = true;
		if(list.size() <= 50){
			String message = book.getImei()+":WN:WN&&A";
			String sql = "insert into t_phonebook (studentcode,imei,incardcode,incellphone,remark) values (:studentcode,:imei,:incardcode,:incellphone,:remark) ";
			message += "&&"+getMesRemark(book.getRemark())+"&&"+book.getIncellphone();
			message += "##";
			SeniorMessageSender.sendMessage(message);
			int n = getDao().executeSQL(sql,book);
			if(n == -1){
				flag = false;
			}else{
				setToCardPhonebooks(book.getImei());
			}
		}else{
			flag = false;
		}
		return flag;
	}
	public void setToCardPhonebooks(String imei){
		TCard card = new TCard();
		card.setImei(imei);
		List<TPhonebook> books = getPhonebooks(card);
		String message = imei+":WN:WN&&A";
		for (int i = 0; i < books.size(); i++) {
			TPhonebook book = books.get(i);
			message += "&&"+getMesRemark(book.getRemark())+"&&"+book.getIncellphone();
		}
		message += "##";
		SeniorMessageSender.sendMessage(message);
	}
	public boolean updatePhonebook(TPhonebook book) {
		boolean flag = true;
		TPhonebook b = (TPhonebook) getDao().update(book);
		if(b == null){
			flag = false;
		}else{
			setToCardPhonebooks(b.getImei());
			flag = true;
		}
		return flag;
	}
	public boolean deletePhonebooks(List<TPhonebook> books) {
		TPhonebook p = books.get(0);
		String message = p.getImei()+":WN:WN&&D";
		for (int i = 0; i < books.size(); i++) {
			TPhonebook book = books.get(i);
			message += "&&"+book.getIncellphone();
		}
		String sql = "DELETE FROM t_phonebook WHERE imei :imei";
		message += "##";
		SeniorMessageSender.sendMessage(message);
		boolean flag = true;
		Map<String,String> map = new HashMap<String, String>();
		map.put("imei", p.getImei());
		int n = getDao().executeSQL(sql,map);
		if(n == -1){
			flag = false;
		}
		return flag;
	}

	public boolean addPhonebookTmps(List<TPhonebooktemp> booktemps) {
		deletePhonebookTmps(booktemps);
		boolean flag = true; 
		TPhonebooktemp p = booktemps.get(0);
		String message = p.getImei()+":WN:WN&&A";
		String sql = "insert into t_phonebook (studentcode,imei,incardcode,incellphone,remark) values ";
		for (int i = 0; i < booktemps.size(); i++) {
			TPhonebooktemp book = booktemps.get(i);
			message += "&&"+getMesRemark(book.getRemark())+"&&"+book.getIncellphone();
			sql += "('";
			sql += book.getStudentcode();
			sql += "','";
			sql += book.getImei();
			sql += "','";
			sql += book.getIncardcode();
			sql += "','";
			sql += book.getIncellphone();
			sql += "','";
			sql = dealRemark(sql,book.getRemark());
		}
		message += "##";
		SeniorMessageSender.sendMessage(message);
		sql = sql.substring(0, sql.length()-1);
		int n = getDao().executeSQL(sql);
		if(n == -1){
			flag = false;
		}
		return flag;
	}

	public boolean deletePhonebookTmps(List<TPhonebooktemp> booktmps) {
		TPhonebooktemp p = booktmps.get(0);
		String message = p.getImei()+":WN:WN&&D";
		for (int i = 0; i < booktmps.size(); i++) {
			TPhonebooktemp book = booktmps.get(i);
			message += "&&"+book.getIncellphone();
		}
		String sql = "DELETE FROM t_phonebook WHERE imei ='"+p.getImei()+"'";
		message += "##";
		Map<String,String> map = new HashMap<String, String>();
		map.put("imei", p.getImei());
		SeniorMessageSender.sendMessage(message);
		boolean flag = true;
		int n = getDao().executeSQL(sql);
		if(n == -1){
			flag = false;
		}
		return flag;
	}
	
	public String dealRemark(String sql,String remark){
		if(remark == null){
			sql = sql.substring(0, sql.length()-1);
			remark = "null";
			sql += remark + "),";
		}else {
			sql += remark;
			sql += "'),";
		}
		return sql;
	}
	public String getMesRemark(String remark){
		if(remark == null){
			remark = "";
		}
		return remark;
	}
	@SuppressWarnings("unchecked")
	public List<TFamilyphone> getFamilyphones(TFamilyphone p){
		List<TFamilyphone> phones = new ArrayList<TFamilyphone>();
		String sql = "SELECT tc.cellphone,tf.imei,tf.familyphone,tf.remark FROM t_familyphone tf,t_card tc WHERE tf.imei = :imei AND tf.imei = tc.imei";
		List<Object[]> list = getDao().queryBySQL(sql,p);
		if(list.size() > 0){
			for (int i = 0; i < list.size(); i++) {
				Object[] obj = list.get(i);
				TFamilyphone tp = new TFamilyphone();
				tp.setNumber(String.valueOf(obj[0]));
				tp.setImei(String.valueOf(obj[1]));
				tp.setFamilyphone(String.valueOf(obj[2]));
				tp.setRemark(String.valueOf(obj[3]));
				phones.add(tp);
				String str = RedisUtil.getInstance().getHashKeyValue(RedisKeyConstant.FAMILYPHONE_OLD+DateUtil.getFormatDate(new Date(), "yyyy-MM-dd"),tp.getNumber()+i);
				if(str == null || str.length() == 0){
					if(tp.getFamilyphone().length() > 0){
						RedisUtil.getInstance().setHashKeyValue(RedisKeyConstant.FAMILYPHONE_OLD+DateUtil.getFormatDate(new Date(), "yyyy-MM-dd"),tp.getNumber()+i, tp.getFamilyphone());
					}
				}
			}
		}else{
			String sql2 = "SELECT tc.cellphone,tc.imei FROM t_card tc WHERE ";
			if(p.getImei() != null && p.getImei().length() > 0){
				sql2 += "tc.imei = :imei";
			}
			if(p.getNumber() != null && p.getNumber().length() > 0){
				sql2 += "tc.cellphone = :cellphone"; 
			}
			List<Object[]> list2 = getDao().queryBySQL(sql2,p);
			for (int i = 0; i < list2.size(); i++) {
				Object[] obj = list2.get(i);
				TFamilyphone tp = new TFamilyphone();
				tp.setNumber(String.valueOf(obj[0]));
				tp.setImei(String.valueOf(obj[1]));
				phones.add(tp);
				String str = RedisUtil.getInstance().getHashKeyValue(RedisKeyConstant.FAMILYPHONE_OLD+DateUtil.getFormatDate(new Date(), "yyyy-MM-dd"),tp.getNumber()+i);
				if(str == null || str.length() == 0){
					if(tp.getFamilyphone().length() > 0){
						RedisUtil.getInstance().setHashKeyValue(RedisKeyConstant.FAMILYPHONE_OLD+DateUtil.getFormatDate(new Date(), "yyyy-MM-dd"),tp.getNumber()+i, tp.getFamilyphone());
					}
				}
			}
		}
		return phones;
	}
	public void updateFamilyphonesFlag(List<TFamilyphone> phones){
		String sql = "";
		TFamilyphone tp = phones.get(0);
		List<TFamilyphone> oldphones = getFamilyphones(tp);
		TFamilyphone oldphone =  oldphones.get(0);
		for (int i = 0; i < phones.size(); i++) {
			TFamilyphone phone = phones.get(i);
			sql = "UPDATE t_familyphone SET flag = :flag ,msg = :msg "
					+ "where imei = :imei and familyphone = :familyphone";
			int j = getDao().executeSQL(sql,phone);
			if(j == -1){
				System.out.println(phone.getFamilyphone()+"--------ok");
			}else{
				System.out.println(phone.getFamilyphone()+"--------ok");
			}
			
		}
	}
	public boolean addFamilyphones(List<TFamilyphone> phones) {
		boolean flag = true;
		TFamilyphone p = phones.get(0);
		List<TFamilyphone> oldphones = getFamilyphones(p);
		deleteFamilyphones(phones);
		String message = p.getImei()+":FN:FN&&A";
		String sql = "insert into t_familyphone (imei,familyphone,flag,msg,remark) values ";
		for (int i = 0; i < phones.size(); i++) {
			Date time = new Date();
			TFamilyphone phone = phones.get(i);
			TFamilyphone oldphone = null;
			try {
				oldphone = oldphones.get(i);
			} catch (Exception e) {
				oldphone =  oldphones.get(0);
				oldphone.setFamilyphone(null);
			}
			if(!phone.getFamilyphone().equalsIgnoreCase(oldphone.getFamilyphone())){
				phone.setOperation("1");
				phone.setTime(DateUtil.getFormatDate(time, "yyyyMMddHHmmss"));
				phone.setNumber(oldphone.getNumber());
				RedisUtil.getInstance().setHashKeyValue(RedisKeyConstant.FAMILYPHONE_NEW+DateUtil.getFormatDate(time, "yyyy-MM-dd"),phone.getNumber()+i,
						GsonUtils.getInstance().toJson(phone));
			}
			message += "&&"+getMesRemark(phone.getRemark())+"&&"+phone.getFamilyphone();
			sql += "('";
			sql += phone.getImei();
			sql += "','";
			sql += phone.getFamilyphone();
			if(phone.getFamilyphone().length() == 11){
				sql += "','2','请等待审核','";
			}else{
				sql += "','0','请输入正确的手机号码','";
			}
			sql = dealRemark(sql,phone.getRemark());
		}
		message += "##";
		SeniorMessageSender.sendMessage(message);
		sql = sql.substring(0, sql.length()-1);
		int n = getDao().executeSQL(sql);
		if(n == -1){
			flag = false;
		}
		return flag;
	}
//	public boolean saveFtpFile(List<TFamilyphone> list){
//		boolean flag = false;
//		int newint = 0;
//		//记录第几个文件
//		String s = RedisUtil.getInstance().getString(RedisKeyConstant.FTP_FILENAME);
//		if(s == null || s.length() == 0){
//			RedisUtil.getInstance().setString(RedisKeyConstant.FTP_FILENAME, "1");
//		}else{
//			newint = Integer.parseInt(s)+1;
//			RedisUtil.getInstance().setString(RedisKeyConstant.FTP_FILENAME, String.valueOf(newint));
//		}
//		String stint = RedisUtil.getInstance().getString(RedisKeyConstant.FTP_FILENAME);
//		String str = "0000"+stint;
//		String newstr = str.substring(str.length()-4,str.length());
//		String f = Freemark.class.getResource("/").getPath();
//		File file = new File(f);
//		Freemark freemark = new Freemark(new File(file.getPath()+"/template/"));  
//		Date time= new Date();
//		String filename = "QQHM_XHK_"+DateUtil.getFormatDate(time, "yyyyMMdd")+"_"+newstr+"."+newstr;
//        freemark.setTemplateName("familynums.ftl");  
//        freemark.setFileName(filename);  
//        freemark.setFilePath(ConfigUtil.getProperty("ftp","temp"));  
//        //生成word  
//        freemark.createFile(list);  
//        if(newint == 9999){
//			RedisUtil.getInstance().setString(RedisKeyConstant.FTP_FILENAME, "");
//			//剪切文件到上传目录并上传文件
//			synchronized (this) {
//				copy(ConfigUtil.getProperty("ftp","temp"),ConfigUtil.getProperty("ftp","uploads"));
//				RedisUtil.getInstance().setString(RedisKeyConstant.FTP_FILENAME, "");
//				UpFileJob.successmap = new HashMap<String, String>();
//				UpFileJob.upload();
//				while(true){
//					if(UpFileJob.retry == false){
//						break;
//					}else{
//						UpFileJob.upload();
//					}
//				}
//			}
//		}
//		return flag;
//	}
//	public  void copy(String path, String copyPath){
//		File filePath = new File(path);
//		DataInputStream read ;
//		DataOutputStream write;
//		if(filePath.isDirectory()){
//			File[] list = filePath.listFiles();
//			for(int i=0; i<list.length; i++){
//				String newPath = path + File.separator + list[i].getName();
//				String newCopyPath = copyPath + File.separator + list[i].getName();
//				copy(newPath, newCopyPath);
//			}
//		}else if(filePath.isFile()){
//			try {
//				read = new DataInputStream(new BufferedInputStream(new FileInputStream(path)));
//				write = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(copyPath)));
//				String s = IOUtils.toString(read, "utf-8");
//				IOUtils.write(s, write);
//				read.close();
//				write.close();
//				System.out.println(path+"---OK!");
//				//删除原文件
//				filePath.delete();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}else{
//			System.out.println("文件路径不正确");
//		}
//	}
	public boolean deleteFamilyphones(List<TFamilyphone> phones) {
		TFamilyphone p = phones.get(0);
		String message = p.getImei()+":FN:FN&&D";
		for (int i = 0; i < phones.size(); i++) {
			TFamilyphone phone = phones.get(i);
			message += "&&"+phone.getFamilyphone();
		}
		message += "##";
		SeniorMessageSender.sendMessage(message);
		String sql = "DELETE FROM t_familyphone WHERE imei =:imei";
		boolean flag = true;
		int n = getDao().executeSQL(sql,p);
		if(n == -1){
			flag = false;
		}
		return flag;
	}

	public boolean addSosphones(List<TSosphone> soss) {
		deleteSosphones(soss);
		boolean flag = true;
		TSosphone p = soss.get(0);
		String message = p.getImei()+":SOS:SOS,A";
		String sql = "insert into t_sosphone (imei,sosphone,remark) values ";
		for (int i = 0; i < soss.size(); i++) {
			TSosphone sos = soss.get(i);
			message += ","+sos.getSosphone();
			sql += "('";
			sql += sos.getImei();
			sql += "','";
			sql += sos.getSosphone();
			sql += "','";
			sql = dealRemark(sql,sos.getRemark());
		}
		sql = sql.substring(0, sql.length()-1);
		message += "#";
		SeniorMessageSender.sendMessage(message);
		int n = getDao().executeSQL(sql);
		if(n == -1){
			flag = false;
		}
		return flag;
	}

	public boolean deleteSosphones(List<TSosphone> soss) {
		TSosphone p = soss.get(0);
		String message = p.getImei()+":SOS:SOS&&D";
		for (int i = 0; i < soss.size(); i++) {
			TSosphone sos = soss.get(i);
			message += "&&"+sos.getSosphone();
		}
		String sql = "DELETE FROM t_sosphone WHERE imei =:imei";
		message += "#";
		SeniorMessageSender.sendMessage(message);
		boolean flag = true;
		int n = getDao().executeSQL(sql,p);
		if(n == -1){
			flag = false;
		}
		return flag;
	}
	public boolean sendTextToCard(TCard card) {
		TUserStudent tus = getUSIByImei(card.getImei());
		TMessage me = new TMessage();
		me.setType("5");
		me.setSendcode(tus.getUsercode());
		me.setReceivecode(tus.getStudentcode());
		me.setContent(card.getRemark());
		Date now = new Date();
		me.setIdatetime(now.getTime()/1000);
		String sql = "INSERT INTO t_message (id,type,sendcode,receivecode,content,idatetime) VALUES "
				+ "(NULL,:type,:sendcode,:receivecode,:content,:idatetime)";
		int i = getDao().executeSQL(sql,me);
		boolean flag = true;
		if(i == -1){
			flag = false;
		}
		String message = card.getImei()+":TEXT:"+card.getRemark();
		SeniorMessageSender.sendMessage(message);
		return flag;
	}

	public boolean setCardWork(TBdworkhour work) {
		System.out.println(GsonUtils.getInstance().toJson(work));
		String s = getTimestr(work.getStart1())+getTimestr(work.getStop1())+"|"+getTimestr(work.getStart2())+getTimestr(work.getStop2())+"|"+getTimestr(work.getStart3())+getTimestr(work.getStop3())+"|"+getTimestr(work.getStart4())+getTimestr(work.getStop4())+"|"+
				getTimestr(work.getStart5())+getTimestr(work.getStop5())+"|"+getTimestr(work.getStart6())+getTimestr(work.getStop6())+"|"+getTimestr(work.getStart7())+getTimestr(work.getStop7())+"|"+getTimestr(work.getStart8())+getTimestr(work.getStop8())+"]"+
				getTimestr(work.getStart9())+getTimestr(work.getStop9())+"|"+getTimestr(work.getStart10())+getTimestr(work.getStop10())+"|"+getTimestr(work.getStart11())+getTimestr(work.getStop11())+"|"+getTimestr(work.getStart12())+getTimestr(work.getStop12())+"|"+
				getTimestr(work.getStart13())+getTimestr(work.getStop13())+"|"+getTimestr(work.getStart14())+getTimestr(work.getStop14())+"|"+getTimestr(work.getStart15())+getTimestr(work.getStop15())+"|"+getTimestr(work.getStart16())+getTimestr(work.getStop16())+"]"+
				getTimestr(work.getStart17())+getTimestr(work.getStop17())+"|"+getTimestr(work.getStart18())+getTimestr(work.getStop18())+"|"+getTimestr(work.getStart19())+getTimestr(work.getStop19())+"|"+getTimestr(work.getStart20())+getTimestr(work.getStop20())+"|"+
				getTimestr(work.getStart21())+getTimestr(work.getStop21())+"|"+getTimestr(work.getStart22())+getTimestr(work.getStop22())+"|"+getTimestr(work.getStart23())+getTimestr(work.getStop23())+"|"+getTimestr(work.getStart24())+getTimestr(work.getStop24())+"}";
//		String mess = work.getCardcode()+":TIME:TIME|"+work.getWork()+"|"+work.getWork()+"|"+s;
		String mess = work.getCardcode()+":TIME:TIME|"+work.getWork()+"|1|"+s;
		SeniorMessageSender.sendMessage(mess);
		boolean flag = true;
		String hql = "From TBdworkhour work where work.cardcode = :cardcode and work.work = :work";
		TBdworkhour tw = (TBdworkhour) getDao().queryFirstByHQL(hql,work);
		TBdworkhour tbdworkhour = null;
		if(tw != null){
			for (Field f : work.getClass().getDeclaredFields()) {
			    f.setAccessible(true);
			    try {
					if (f.get(work) != null && !f.getName().equalsIgnoreCase("serialVersionUID")) {
					   f.set(tw, f.get(work));
					}
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}
			tbdworkhour = (TBdworkhour) getDao().update(tw);
		}
		if(tbdworkhour == null){
			flag  = false;
		}
		return flag;
	}

	public TBdworkhour getCardWork(TBdworkhour work) {
		String hql = "From TBdworkhour work where work.cardcode = :cardcode and work.work = :work";
		TBdworkhour tw = (TBdworkhour) getDao().queryFirstByHQL(hql,work);
		return tw;
	}
	public String getTimestr(String time){
		String result = "";
		if(time != null && time.length() > 0){
			String[] times = time.split(":");
			result =times[0]+times[1];
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	public List<TFamilyphone> getFamilyphones(TCard card) {
		List<TFamilyphone> result = new ArrayList<TFamilyphone>();
		if(card.getImei().length() > 0 && card.getImei() != null){
			String sql = "select * from t_familyphone where imei = :imei";
			List<Object[]> list = getDao().queryBySQL(sql,card);
			for (Object[] obj:list) {
				TFamilyphone tfh = new TFamilyphone();
				tfh.setId(Long.valueOf(String.valueOf(obj[0])));
				tfh.setImei(String.valueOf(obj[1]));
				tfh.setFamilyphone(String.valueOf(obj[2]));
				tfh.setRemark(String.valueOf(obj[3]));
				tfh.setFlag(String.valueOf(obj[4]));
				tfh.setMsg(String.valueOf(obj[5]));
				result.add(tfh);
			}
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	public List<TSosphone> getSosphones(TCard card) {
		List<TSosphone> result = new ArrayList<TSosphone>();
		if(card.getImei().length() > 0 && card.getImei() != null){
			String sql = "select * from t_sosphone where imei=:imei";
			List<Object[]> list = getDao().queryBySQL(sql,card);
			for (Object[] obj:list) {
				TSosphone tfh = new TSosphone();
				tfh.setId(Long.valueOf(String.valueOf(obj[0])));
				tfh.setImei(String.valueOf(obj[1]));
				tfh.setSosphone(String.valueOf(obj[2]));
				tfh.setRemark(String.valueOf(obj[3]));
				result.add(tfh);
			}
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	public List<TPhonebook> getPhonebooks(TCard card) {
		List<TPhonebook> result = new ArrayList<TPhonebook>();
		if(card.getImei().length() > 0 && card.getImei() != null){
			String sql = "select * from t_phonebook where imei=:imei";
			List<Object[]> list = getDao().queryBySQL(sql,card);
			for (Object[] obj:list) {
				TPhonebook tfh = new TPhonebook();
				tfh.setId(Long.valueOf(String.valueOf(obj[0])));
				tfh.setStudentcode(String.valueOf(obj[1]));
				tfh.setImei(String.valueOf(obj[2]));
				tfh.setIncardcode(String.valueOf(obj[3]));
				tfh.setIncellphone(String.valueOf(obj[4]));
				tfh.setRemark(String.valueOf(obj[5]));
				result.add(tfh);
			}
		}
		return result;
	}

	public List<Rings> getAllRings() {
		List<Rings> result = new ArrayList<Rings>();
		for (int i = 1; i < 11; i++) {
			Rings r = new Rings();
			r.setRing(String.valueOf(i));
			r.setRingurl("/card/ring/"+String.valueOf(i)+".swf");
			result.add(r);
		}
		return result;
	}

	public boolean sendWarnType(Mstatus mstatus) {
		TUserStudent tus = getUSIByImei(mstatus.getImei());
		MessageUtil.appidList = new ArrayList<Integer>();
		MessageUtil.appidList.add(MessageUtil.appids.get("userid"));
		MessageUtil.sendToClient(mstatus.getAddress(),"warn&"+GsonUtils.getInstance().toJson(mstatus),tus.getTo(),1,0,0L);
		return true;
	}
	
	public boolean sendCmpp(CmppData cd){
		TUserStudent tus = getUSIByImei(cd.getImei());
		if(cd.getStatus() == 1){
			CmppUtil.sendToCmpp("您的孩子："+tus.getStuname()+"，"+cd.getContent(), tus.getTo());
		}else{
			CmppUtil.sendToCmpp("您的孩子："+tus.getStuname()+"，"+cd.getContent(), tus.getTo());
		}
		return CmppUtil.sendToCmpp(cd.getContent(),cd.getTo());
	}
	public boolean setGPS(String imei, String gpsstatus) {
		if(gpsstatus.equalsIgnoreCase("ON")){
			gpsstatus = "ON,300";
			//离校
//			CmppUtil.sendToCmpp("您的孩子："+tus.getStuname()+"已经离校", tus.getTo());
		}
//		CmppUtil.sendToCmpp("您的孩子："+tus.getStuname()+"已经进校", tus.getTo());
		String message = imei+":GPS:GPS"+gpsstatus+"#";
		SeniorMessageSender.sendMessage(message);
		return true;
	}
	public boolean getGPS(String imei) {
		String message = imei+":GPS:STATUS#";
		SeniorMessageSender.sendMessage(message);
		return true;
	}

	public String queryYE_old(String imei) {
		if(imei != null && imei.length() > 0){
			String sql = "select remark from t_card where imei = '"+imei+"'";
			List list = getDao().queryBySQL(sql);
			if(list.size() > 0){
				String result = String.valueOf(list.get(0));
				return result;
			}else{
				return null;
			}
		}else{
			return null;
		}
		
	}

	public boolean queryYE(String imei) {
		String message = imei+":FW:FW,10086,CXYE#";
		SeniorMessageSender.sendMessage(message);
		String sql = "UPDATE t_card SET remark='' WHERE imei='"+imei+"'";
		int i = getDao().executeSQL(sql);
		return i == -1 ? false : true;
	}

	/**删除白名单信息
	 * @author:wuqiwei
	 * @param @param book
	 * @param @return
	 * @date:2016年8月19日下午4:25:22
	*/
	public boolean deleteWhiteListInfo(TPhonebook book) {
		boolean flag = false;
		String sql = "DELETE FROM t_phonebook WHERE studentcode = '"+book.getStudentcode()+"' AND imei = '"+book.getImei()+"' AND incardcode = '"+book.getIncardcode()+"'";
		int a =getDao().executeSQL(sql);
		if( a > 0){
			flag = true;
		}
		return flag;
	}

//	@SuppressWarnings("static-access")
//	public boolean downFile() {
//		DownFileJob.successmap = new HashMap<String, String>();
//		DownFileJob.downloads(UpFileJob.successmap);
//		while(true){
//			if(DownFileJob.retry == false){
//				break;
//			}else{
//				DownFileJob.downloads(DownFileJob.failedmap);
//			}
//		}
//		DownFileJob.dealDownLoads(DownFileJob.successmap);
//		return true;
//	}

}
